package cool.mtc.minghe.web.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import cool.mtc.core.exception.ServiceException;
import cool.mtc.core.result.ResultConstant;
import cool.mtc.minghe.service.service.websocket.WebSocketService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.stereotype.Component;

/**
 * @author 明河
 */
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 99)
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CustomChannelInterceptor implements ChannelInterceptor {
    private static final String HEADER_PARAM_ID = "id";
    private static final String HEADER_PARAM_TOKEN = "token";

    private final WebSocketService webSocketService;

    @SneakyThrows
    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        if (null == accessor) {
            return message;
        }
        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
            String id = accessor.getFirstNativeHeader(HEADER_PARAM_ID);
            WebSocketPrincipal principal = new WebSocketPrincipal();
            principal.setId(id);
            principal.setSessionId(accessor.getSessionId());
            accessor.setUser(principal);
            throw new WebSocketException(ResultConstant.A0301);
        }
        return message;
    }
}
